package com.yc.yjh.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.yc.yjh.bean.UploadProperties;
import com.yc.yjh.entity.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@CrossOrigin
@RestController
public class UploadController {

    @Resource
    UploadProperties uploadProperties;

    @PostMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile file,String dir){
        String endpoint =uploadProperties.getEndpoint();

        String accessKeyId=uploadProperties.getAccessKeyId();
        String accessSecret=uploadProperties.getAccessSecret();

        String bucketName=uploadProperties.getBucketName();
        final String fileName =dir+"/"+ UUID.randomUUID().toString().replaceAll("-", "");
        String url="http://"+bucketName+".oss-cn-chengdu.aliyuncs.com/"+fileName;
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessSecret);

        try {
            final InputStream inputStream = file.getInputStream();
            final PutObjectRequest request = new PutObjectRequest(bucketName,fileName,inputStream);
            final PutObjectResult result = ossClient.putObject(request);
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return "文件上传失败!";
        }finally {
            if (ossClient!=null)
                ossClient.shutdown();
        }
    }
}
